#include <sys/types.h>
#include <sys/ipc.h>
#include <string>
#include <string.h>
#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>

using namespace std;

const char *pathname = "/home/linying/mylinuxstudy";
int proj_id = 310;
const int SIZE = 4096;

// 通过什么什么算法，获取k
key_t GetShmKeyorDie()
{
    key_t key = ftok(pathname, proj_id);
    if (key < 0)
    {
        cerr << "ftok error, errno : " << errno << ", error string: " << strerror(errno) << endl;
        exit(1);
    }
    return key;
}

// 将获取到的k转换成16进制。0xxx
string ToHex(key_t key)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", key);
    return buffer;
}

//创建共享内粗能或者创建失败
int GetShmOrDie(key_t key, ssize_t size, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid < 0)
    {
        cerr << "shmid error, errno : " << errno << ", error string: " << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

//创建共享内存
int CreatShm(key_t key, ssize_t size)
{
    return GetShmOrDie(key,size,IPC_CREAT | IPC_EXCL | 0666);
}

//获取共享内存id
int GetShm(key_t key, ssize_t size)
{
    return GetShmOrDie(key, size, IPC_CREAT);
}

//共享内存debug
void ShmDebug(int shmid)
{
    struct shmid_ds shmds;
    int n = shmctl(shmid, IPC_STAT, &shmds);
    if (n < 0)
    {
        std::cerr << "shmctl error" << std::endl;
        return;
    }
    std::cout << "shmds.shm_segsz: " << shmds.shm_segsz << std::endl;
    std::cout << "shmds.shm_nattch:" << shmds.shm_nattch << std::endl;
    std::cout << "shmds.shm_ctime:" << shmds.shm_ctime << std::endl;
    std::cout << "shmds.shm_perm.__key:" << ToHex(shmds.shm_perm.__key) << std::endl;
}

//删除共享内存
void DeleteShm(int shmid)
{
    int n = shmctl(shmid, IPC_RMID, nullptr);
    if(n < 0) cerr << "shmctl error" << endl;
    else cout << "shmctl delete shm success, shmid: " << shmid << endl;
}

//将共享内存挂到映射到进程
void* ShmAttach(int shmid)
{
    void* addr = shmat(shmid, nullptr, 0);
    if((long long int)addr == -1)
    {
        cerr<< "shamt fail errno" << endl;
        return nullptr;
    }
    return addr;
}

void ShmDetach(void* addr)
{
    int n = shmdt(addr);
    if(n < 0) cerr << "shmdt error" << endl;
}
